import React, { useEffect, useState } from 'react'; // eslint-disable-line
import { createPortal } from 'react-dom';
import stateBridge from '../utils/stateBridge';

function getDisplayName(WrappedComponent) {
    return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
/**
 * 这个组件还要完成一个功能，监听需要挂载的dom元素是否已经被创建了
 * 当一个vue组件created成功的时候
 */
export default function connectPortal(WrappedComponent, elementId) {
    // class PortalWrapper extends React.PureComponent {

    //     render() {
    //         return createPortal(<WrappedComponent {...this.props} />, container);
    //     }
    // }
    function PortalWrapper(props) {
        const [element, setEle] = useState(null);
        useEffect(() => {
            const unbind = stateBridge.onDomReady(elementId, (domEle) => {
                if (!domEle) console.error('dom not ready yet.please check id ', elementId)
                setEle(domEle)
            });
            return unbind;
        }, [])
        if (!element) return null;
        return createPortal(<WrappedComponent {...props} />, element);
    }
    PortalWrapper.displayName = `PortalWrapper(${getDisplayName(WrappedComponent)})`;
    return PortalWrapper;
}